package com.eipc;


import org.androidpn.sdk.Constants;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.IBinder;
import android.util.Log;

import com.eipc.info.R;
import com.eipc.model.Response;
import com.eipc.util.DBHelper;
import com.eipc.util.HttpManager;
import com.eipc.util.JsonParse;
import com.eipc.util.MyLog;
import com.eipc.util.Tools;

public class FetchReplyService1 extends Service {
	private DBHelper mDB;
	
	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}
	
	@Override
	public void onCreate() {
		super.onCreate();
//		mDB = new DBHelper(this);
		mDB = DBHelper.getInstance(this);
		 
	}
	
	@Override
	public void onStart(Intent intent, int startId) {
		new PollingReplyTask().execute();	
		Log.e("-----------do FetchReplyService-----------------",Tools.getCurrentTimeString());
	}
	
	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}
	
	class PollingReplyTask extends AsyncTask<Void, Void, Void>{
		private String mResult;
		@Override
		protected Void doInBackground(Void... params) {
			try {
				SharedPreferences sdkPreferences = getSharedPreferences(Constants.SDK_PREFERENCES, Context.MODE_PRIVATE);
				String mobileID = sdkPreferences.getString(Constants.XMPP_USERNAME,"");
				String rbs = mDB.getUploadReply();
				if(rbs!=null){
					HttpManager.uploadReply(getString(R.string.url_upload_reply),mobileID,rbs,mDB);
				}
			} catch (Exception e) {
				MyLog.error(FetchReplyService1.class,"",e);
			}
			return null;
		}
		
		@Override
		protected void onPostExecute(Void result) {
			if(mResult!=null && !"".equals(mResult)){
				Response resp = JsonParse.parseRespnse(mResult);
				if(resp!=null&&resp.success){
				}else{
						Log.e(this.getClass().getName()+" polling failure : ",resp.toString());
				}
			}else{
				Log.e(this.getClass().getName()+" polling failure : ","mResult is null");
			}
		}
		
	}
}
